import { uploadImage } from '../../api/api';

Page({
    data: {
        checkinId: null,
        checkinInfo: {},
        checkinStatus: '', // 空字符串表示初始状态，loading表示加载中，success表示成功，failed表示失败
        signTime: '',
        failReason: '', // 失败原因
        faceImagePath: '' // 拍摄的人脸照片临时路径
    },

    onLoad: function(options) {
        const checkinId = Number(options.id) || 0;
        this.setData({
            checkinId: checkinId
        });

        this.loadCheckinInfo();

        // 获取摄像头权限
        wx.authorize({
            scope: 'scope.camera',
            success: () => {
                // 授权成功
            },
            fail: () => {
                wx.showToast({
                    title: '请授权摄像头权限',
                    icon: 'none',
                    duration: 2000
                });
            }
        });
    },

    // 加载签到信息
    loadCheckinInfo: function() {
        // 模拟数据，实际应该从服务器获取
        const checkinInfo = {
            id: this.data.checkinId,
            checkinName: '第三周周三课堂签到',
            formattedStartTime: '2023-10-18 14:00',
            formattedEndTime: '2023-10-18 15:30',
            courseName: '计算机组成原理'
        };

        this.setData({
            checkinInfo: checkinInfo
        });
    },

    // 开始签到
    startCheckin: function() {
        this.setData({
            checkinStatus: 'loading'
        });

        // 使用相机拍摄人脸
        const ctx = wx.createCameraContext();
        ctx.takePhoto({
            quality: 'high',
            success: (res) => {
                // 保存照片临时路径
                this.setData({
                    faceImagePath: res.tempImagePath
                });

                // 上传人脸图片
                this.uploadFaceImage(res.tempImagePath);
            },
            fail: (error) => {
                console.error('拍照失败', error);
                this.setData({
                    checkinStatus: 'failed',
                    failReason: '拍照失败，请重试'
                });
            }
        });
    },

    // 上传人脸图片
    uploadFaceImage: function(imagePath) {
        // 使用新的图片上传API
        uploadImage({
            file: imagePath,
            type: 'face',
            success: (data) => {
                // 图片上传成功，调用签到接口
                this.doFaceCheckin(data.imageId);
            },
            fail: (error) => {
                this.setData({
                    checkinStatus: 'failed',
                    failReason: error.errMsg || '图片上传失败，请重试'
                });
            }
        });
    },

    // 执行人脸签到
    doFaceCheckin: function(imageId) {
        // 获取学生ID，实际开发中应从用户信息中获取
        const studentId = wx.getStorageSync('userInfo').id || '1001';

        // 调用签到接口
        wx.request({
            url: 'https://api.example.com/api/student/checkin/do',
            method: 'POST',
            data: {
                studentId: studentId,
                checkinId: this.data.checkinId,
                imageId: imageId
            },
            success: (res) => {
                const { code, data, message } = res.data;

                if (code === 0 && data) {
                    if (data.status === 'success') {
                        // 签到成功
                        this.setData({
                            checkinStatus: 'success',
                            signTime: data.signTime || this.getCurrentTime()
                        });
                    } else {
                        // 签到失败
                        this.setData({
                            checkinStatus: 'failed',
                            failReason: data.message || '人脸识别失败，请确保光线充足并正对摄像头'
                        });
                    }
                } else {
                    // 请求成功但业务失败
                    this.setData({
                        checkinStatus: 'failed',
                        failReason: message || '签到失败，请重试'
                    });
                }
            },
            fail: (error) => {
                // 网络请求失败
                this.setData({
                    checkinStatus: 'failed',
                    failReason: '网络错误，请稍后重试'
                });
            }
        });
    },

    // 获取当前时间，格式为 HH:MM
    getCurrentTime: function() {
        const now = new Date();
        const hour = now.getHours().toString().padStart(2, '0');
        const minute = now.getMinutes().toString().padStart(2, '0');
        return `${hour}:${minute}`;
    },

    // 重试签到
    retryCheckin: function() {
        this.setData({
            checkinStatus: '',
            failReason: '',
            faceImagePath: ''
        });
    },

    // 返回列表
    backToList: function() {
        wx.navigateBack();
    },

    // 相机错误
    cameraError: function(e) {
        console.error('相机错误', e.detail);
        this.setData({
            checkinStatus: 'failed',
            failReason: '相机启动失败，请检查权限并重试'
        });
    }
});